import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jd_shop/widget/LoadingWidget.dart';

import '../../model/GoodsList.dart';
import '../../net/Config.dart';
import '../../net/MallmsService.dart';
import '../../routers/AppRoutes.dart';
import '../../services/ScreenAdaper.dart';
import '../../widget/TextWidget.dart';

class SearchGoods extends StatefulWidget {
  Map arguments;

  SearchGoods({super.key, required this.arguments});

  @override
  _SearchGoodsState createState() => _SearchGoodsState();
}

class _SearchGoodsState extends State<SearchGoods> {
  int? catId = 0;
  int orderType = 3; // 1价格排序，2销量排序 3综合排序 4更新时间 5评论数
  int saleNum = 1; // 1降序
  int priceOrder = 2; // 1降序，2升序
  int currentPage = 1;
  var cur = 1;
  var tagerSize = 0;
  List<Widget> _ItemGoodsWidgetList = [];
  final ScrollController _scrollController = ScrollController();
  var _hasMore = true;

  @override
  void initState() {
    super.initState();
    // _controller.text = widget.arguments["keyword"];
    catId = widget.arguments["catId"];
    getGoodsListNet();
    _scrollController.addListener(() {
      //上拉加载更多
      if (_scrollController.position.pixels > _scrollController.position.maxScrollExtent - 50) {
        cur++;
        getGoodsListNet();
      }
    });
  }

  void getGoodsListNet() {
    var params = HashMap<String, dynamic>();
    if (catId != 0) {
      params["catId"] = catId;
    }
    params["commonName"] = _controller.text;
    params["orderType"] = orderType;
    params["saleNum"] = saleNum;
    params["priceOrder"] = priceOrder;
    params["currentPage"] = currentPage;
    params["pageSize"] = Config.PAGECOUNT;
    MallmsService.QUERY_GOODS_List(params).then((onValue) {
      tagerSize = onValue!.length;
      if (cur == 1) {
        _scrollController.jumpTo(0);
        _ItemGoodsWidgetList = [];
      }
      for (var element in onValue) {
        _ItemGoodsWidgetList.add(_itemGoodsWidget(element));
      }
      _hasMore = (tagerSize == Config.PAGECOUNT);
      setState(() {});
    });
  }

  final _controller = TextEditingController();

  _searchText() {
    return TextField(
        controller: _controller,
        onChanged: (value) {
          print(value);
        },
        style: const TextStyle(color: Colors.white),
        decoration: const InputDecoration(
          border: InputBorder.none,
          hintText: "请输入搜索内容",
          hintStyle: TextStyle(color: Colors.white),
        ),
        onSubmitted: (value) {
          cur = 1;
          _scrollController.jumpTo(0);
          getGoodsListNet();
        });
  }

  Widget _itemGoodsWidget(GoodsList goodsInfoList) {
    return Container(
        color: Colors.white,
        width: (ScreenAdapter.getScreenWidth() - 30) / 2,
        child: InkWell(
            onTap: () {
              Navigator.pushNamed(context, AppRoutes.GOODS_DETAIL, arguments: {
                "goodsId": goodsInfoList.goodsId,
                "commonId": goodsInfoList.commonId,
              });
            },
            child: Container(
              padding: EdgeInsets.all(ScreenAdapter.width(0)),
              decoration: BoxDecoration(
                  border: Border.all(color: const Color.fromARGB(100, 255, 255, 255), width: 1),
                  borderRadius: BorderRadius.circular(6),
                  color: Colors.white),
              child: Column(
                children: [
                  AspectRatio(
                    aspectRatio: 1 / 1,
                    child: ClipRRect(
                      borderRadius: const BorderRadius.only(topLeft: Radius.circular(5), topRight: Radius.circular(5)),
                      child: Image.network(goodsInfoList.commonImage, fit: BoxFit.cover),
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    alignment: Alignment.topLeft,
                    height: ScreenAdapter.height(40),
                    margin: EdgeInsets.only(top: ScreenAdapter.height(10)),
                    padding: EdgeInsets.only(left: ScreenAdapter.width(10), right: ScreenAdapter.width(10)),
                    child: Text(
                      "${goodsInfoList.commonName}",
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: ScreenAdapter.width(10), right: ScreenAdapter.width(10)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        TextWidget(
                          "¥ ${goodsInfoList.commonPrice}",
                          fontSize: 16,
                          color: Colors.red,
                        ),
                        Text("¥ ${goodsInfoList.commonMarketPrice}",
                            style: const TextStyle(color: Colors.grey, fontSize: 16, decoration: TextDecoration.lineThrough))
                      ],
                    ),
                  ),
                ],
              ),
            )));
  }

  List<String> listTextI = [];

  _lableWrap() {
    for (var i = 0; i < 30; i++) {
      listTextI.add("value$i");
    }
    return Wrap(spacing: 10, runSpacing: 10, children: [
      for (var i = 0; i < listTextI.length; i++)
        Container(
            padding: EdgeInsets.all(ScreenAdapter.width(5)),
            decoration: BoxDecoration(
              border: Border.all(color: const Color(0xFF9F8CFF), width: 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: InkWell(
                onTap: () {
                  // var child = (key.currentWidget as Wrap).children[i];
                  // var text = (((child as Container).child as InkWell).child
                  //         as Container)
                  //     .child as Text;
                  // print(text.data);
                  Fluttertoast.showToast(msg: listTextI[i]);
                  _controller.text = listTextI[i];
                },
                child: Container(
                  padding: EdgeInsets.all(ScreenAdapter.width(0)),
                  child: Text(
                    listTextI[i],
                  ),
                )))
    ]);
  }

  _recProductListWidget() {
    return Container(
      margin: const EdgeInsets.only(left: 10, right: 10),
      child: Wrap(spacing: 10, runSpacing: 10, children: _ItemGoodsWidgetList),
    );
  }

  var selectTabIndex = 0;

  _TabListWidget() {
    return //平均显示 综合 销量 价格 筛选
        SizedBox(
            height: 40,
            child: Row(children: [
              Expanded(
                  child: InkWell(
                onTap: () {
                  setState(() {
                    selectTabIndex = 0;
                    cur = 1;
                    orderType = 3;
                    getGoodsListNet();
                  });
                },
                child: Container(
                  alignment: Alignment.center,
                  child: Text(
                    "综合",
                    style: TextStyle(
                      color: selectTabIndex == 0 ? Colors.red : Colors.black,
                    ),
                  ),
                ),
              )),
              Expanded(
                  child: InkWell(
                onTap: () {
                  setState(() {
                    selectTabIndex = 1;
                    cur = 1;
                    orderType = 2;
                    getGoodsListNet();
                  });
                },
                child: Container(
                  alignment: Alignment.center,
                  child: Text(
                    "销量",
                    style: TextStyle(
                      color: selectTabIndex == 1 ? Colors.red : Colors.black,
                    ),
                  ),
                ),
              )),
              Expanded(
                  child: InkWell(
                onTap: () {
                  setState(() {
                    selectTabIndex = 2;
                    cur = 1;
                    orderType = 1;
                    getGoodsListNet();
                  });
                },
                child: Container(
                  alignment: Alignment.center,
                  child: Text(
                    "价格",
                    style: TextStyle(
                      color: selectTabIndex == 2 ? Colors.red : Colors.black,
                    ),
                  ),
                ),
              )),
              Expanded(
                  child: InkWell(
                onTap: () {
                  setState(() {
                    selectTabIndex = 3;
                  });
                  _scaffoldKey.currentState?.openEndDrawer();
                },
                child: Container(
                  alignment: Alignment.center,
                  //Colors.red
                  child: Text(
                    "筛选",
                    style: TextStyle(
                      color: selectTabIndex == 3 ? Colors.red : Colors.black,
                    ),
                  ),
                ),
              )),
            ]));
  }

  Widget _endDrawer() {
    return Drawer(
      backgroundColor: Colors.white,
      child: Column(children: [
        Container(height: 40, child: Row(children: [Text("6666666666666666666666666666666666666")]))
      ]),
    );
  }

  Future<void> _handleRefresh() async {
    cur = 1;
    getGoodsListNet();
  }

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  //显示加载中的圈圈
  Widget _showMore() {
    if (this._hasMore) {
      return (tagerSize == this._ItemGoodsWidgetList.length - 1) ? const LoadingWidget() : const Text("");
    } else {
      return (tagerSize == this._ItemGoodsWidgetList.length - 1) ? const Text("--我是有底线的--") : const Text("");
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);
    return Scaffold(
      key: _scaffoldKey,
      //添加右边h侧边栏
      endDrawer: _endDrawer(),
      // drawer: const Drawer(
      //   child: Text("6666666666"),
      // ),
      appBar: AppBar(
        //左边返回按键修改
        // leading: IconButton(
        //   icon: const Icon(Icons.add, color: Colors.black),
        //   onPressed: () {
        //     Navigator.pop(context);
        //   },
        // ),
        actions: [
          IconButton(
            icon: const Icon(Icons.close, color: Colors.white),
            onPressed: () {
              _controller.text = "";
              getGoodsListNet();
            },
          ),
        ],
        title: _searchText(),
      ),
      body: Container(
          margin: const EdgeInsets.only(top: 10),
          child: RefreshIndicator(
              onRefresh: _handleRefresh,
              child: ListView(
                controller: _scrollController,
                children: [
                  _TabListWidget(),
                  _recProductListWidget(),
                  Container(
                    height: 60,
                    alignment: Alignment.center,
                    child: Text(_hasMore ? "加载中..." : "没有更多了"),
                  )
                ],
              ))),
    );
  }
}
